package com.hfzy.ihk.common.web.security;

import com.hfzy.ihk.common.web.constants.WebConstant;
import com.hfzy.ihk.common.web.enums.LoginErrorMsgEnum;
import com.hfzy.ihk.common.util.string.StringUtil;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 验证拦截器拦截类（自定义过滤去继承该类）
 *  增加验证码支持
 */
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    // 是否开启验证码功能
    private boolean isOpenValidateCode = true;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        if (isOpenValidateCode) {
            checkValidateCode(request);
        }
        //校验用户名密码
        checkValidateUserNamePassword(request);

        return super.attemptAuthentication(request, response);
    }

    protected void checkValidateCode(HttpServletRequest request) {
        HttpSession session = request.getSession();
        //从session中获取验证码
        String sessionValidateCode = obtainSessionValidateCode(session);
        // 让上一次的验证码失效
        //session.setAttribute(WebConstant.VALIDATE_CODE, null);
        //获取传入进来的验证码
        String validateCodeParameter = obtainValidateCodeParameter(request, WebConstant.VALIDATE_CODE);
        if (StringUtil.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {
            throw new AuthenticationServiceException(LoginErrorMsgEnum.VALIDATE_CODE_ERROR.toStr());
        }
    }

    protected void checkValidateUserNamePassword(HttpServletRequest request){
        String username = obtainValidateCodeParameter(request,WebConstant.USER_NAME);
        String password = obtainValidateCodeParameter(request,WebConstant.PASS_WORD);
        if(username.equals("")) {
            throw new AuthenticationServiceException(LoginErrorMsgEnum.USER_NAME_NULL.toStr());
        }

        if(password.equals("")) {
            throw new AuthenticationServiceException(LoginErrorMsgEnum.PASSWORD_NULL.toStr());
        }
    }

    private String obtainValidateCodeParameter(HttpServletRequest request,String code) {
        Object obj = request.getParameter(code);
        return null == obj ? "" : obj.toString();
    }

    protected String obtainSessionValidateCode(HttpSession session) {
        Object obj = session.getAttribute(WebConstant.VALIDATE_CODE);
        return null == obj ? "" : obj.toString();
    }

}
